//
//  ProductsListViewController.swift
//  iWatchManager
//
//  Created by GujyHy on 2018/1/23.
//  Copyright © 2018年 GujyHy. All rights reserved.
//

import UIKit
import SnapKit
import TZImagePickerController



class ProductsListViewController: UIViewController {
    
    var tableView:UITableView!
    var productsCells:[ProductsListCell] = [ProductsListCell]()
 
    var selectedProductCell:ProductsListCell?
    var selectedPhotos:[UIImage]?
    var selectedAssets:[Any]?
    var delIndex:Int = 0
    
    let productVM:ProductVM = ProductVM()
    
    // MARK: Networking
    func requestData () {
        productVM.requestProductListData("1", finishedSuccess: {
            
            self.title =  self.productVM.product.m_goodsName;
            
            
        }, finishedFail: {
            message in
            
        })
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.buildUI()
//        self.requestData()
        
        self.buildData()
    }
    
 
    
    // MARK: Private
    // build ui
    fileprivate func buildUI(){
        tableView = UITableView(frame: self.view.bounds ,style: UITableViewStyle.plain)
        if #available(iOS 11.0, *){
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.register(ProductsListCell.self, forCellReuseIdentifier: "ProductsListCell")
        tableView.tableFooterView = UIView()
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints{(make) -> Void in
            make.left.right.equalTo(self.view).offset(0)
            make.top.bottom.equalTo(self.view).offset(0)
        }
    }
    fileprivate func buildData(){
        
//        for imglist in productVM.product.m_imgList {
        for index in 0..<3 {
            let cell:ProductsListCell  = ProductsListCell()
            cell.selectionStyle        = .none
//            cell.typeNameLabel.text    = imglist.m_typeName
            cell.typeNameLabel.text    = "图片类型\(index)"
            cell.delegate              = self
            productsCells.append(cell)
        }
         self.tableView.reloadData()
    }
    
    func uploadPhoto(){
        
        
        self.uploadPhotoSuccess()
        
 
    }
    func uploadPhotoSuccess() {
        
        if let cell = self.selectedProductCell {
            cell.selectedPhotos.append(contentsOf: self.selectedPhotos!)
            cell.selectedAssets.append(contentsOf: self.selectedAssets!)
            cell.collectionView.reloadData()
            self.tableView.reloadData()
        }
        
    }
    
    func removePhoto(){
        self.removePhotoSuccess()
    }
    func removePhotoSuccess() {
        
        if let cell = self.selectedProductCell {
            cell.selectedPhotos.remove(at: self.delIndex)
            cell.selectedAssets.remove(at: self.delIndex)
            
            let indexPath = IndexPath(row: self.delIndex, section: 0)
            cell.collectionView.deselectItem(at: indexPath, animated: false)
            cell.collectionView.reloadData()
            self.tableView.reloadData()
        }
    }

    
    
    func presentTZImagePickerController() {
        
        let imagePickerVc = TZImagePickerController(maxImagesCount: 1,
                                                    columnNumber: 3,
                                                    delegate: self,
                                                    pushPhotoPickerVc: true)
        imagePickerVc?.allowPickingVideo               = false
        imagePickerVc?.allowPickingOriginalPhoto       = true
        imagePickerVc?.sortAscendingByModificationDate = true // 照片排列按修改时间升序
        imagePickerVc?.allowCrop  = true // 运行裁剪
        // 设置竖屏下的裁剪尺寸
        let left:CGFloat = 30.0;
        let widthHeight = self.view.frame.size.width - CGFloat(2 * left);
        let top = (self.view.frame.size.height - widthHeight) / 2;
        imagePickerVc?.cropRect = CGRect(x: left, y: top, width: widthHeight, height: widthHeight)
        self.present(imagePickerVc!, animated: true, completion: nil)
        
    }
    func previewPhotos(_ index:Int) {
        // preview photos 预览照片
        if let cell = self.selectedProductCell {
            
            let assets = NSMutableArray.init(array: cell.selectedAssets)
            let photos = NSMutableArray.init(array: cell.selectedPhotos)
            let imagePickerVc = TZImagePickerController(selectedAssets:assets, selectedPhotos: photos, index: index)
            imagePickerVc?.allowPickingOriginalPhoto       = true
            imagePickerVc?.sortAscendingByModificationDate = true // 照片排列按修改时间升序
            
            
            self.present(imagePickerVc!, animated: true, completion: nil)
            
        }
        
//        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//            _selectedPhotos = [NSMutableArray arrayWithArray:photos];
//            _selectedAssets = [NSMutableArray arrayWithArray:assets];
//            _isSelectOriginalPhoto = isSelectOriginalPhoto;
//            [_collectionView reloadData];
//            _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
//            }];
 
    }


    // MARK: Helpers
    // 计算高度
    fileprivate func heightOfCell (_ cell:ProductsListCell) -> CGFloat {
        
        let totalItem            = CGFloat(cell.selectedPhotos.count + 1)
        let labelHeight          = Constant.labelHeight
        let itemHeight           = Constant.getItemWidth(boundWidth: tableView.bounds.size.width)
        let totalRow             = ceil(totalItem / Constant.column) // Constant.totalItem 要动态改变
        let totalTopBottomOffset = Constant.offset + Constant.offset
        let totalSpacing         = CGFloat(totalRow - 1) * Constant.minLineSpacing
        let totalHeight          = ((itemHeight * CGFloat(totalRow)) + totalTopBottomOffset + totalSpacing + labelHeight)
        return totalHeight
    }
}
// MARK: - UITableViewDataSource
extension ProductsListViewController:UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return productsCells.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  1 //productsCells.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let section = indexPath.section
        let cell:ProductsListCell = self.productsCells[section]
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
 
        let section = indexPath.section
        let cell:ProductsListCell = self.productsCells[section]
        let totalHeight  =  self.heightOfCell(cell)
        return totalHeight
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 0))
//        view.backgroundColor = UIColor.init(hex: "dddddd")
        return view
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
}

extension ProductsListViewController: UITableViewDelegate {
    
}

extension ProductsListViewController: ProductsListCellDelegate {
 
    func productListCellAlbumBtnClicked(_ cell:ProductsListCell){
        selectedProductCell = cell
        self.presentTZImagePickerController()
    }
    // delete photo
    func productListCellDeleteItemImage(_ cell:ProductsListCell, withIndex index:Int) {
        
        selectedProductCell = cell
        delIndex            = index
        self.removePhoto()

    }
    // preview photos
    func productListCellPreviewPhotos(_ cell:ProductsListCell, withIndex index:Int){
        selectedProductCell = cell
        self.previewPhotos(index)
    }
    
    
}


extension ProductsListViewController : TZImagePickerControllerDelegate {
    
    // If user picking a video, this callback will be called.
    // If system version > iOS8,asset is kind of PHAsset class, else is ALAsset class.
    // 如果用户选择了一个视频，下面的handle会被执行
    // 如果系统版本大于iOS8，asset是PHAsset类的对象，否则是ALAsset类的对象
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: Any!) {
        
    }
    // If user picking a gif image, this callback will be called.
    // 如果用户选择了一个gif图片，下面的handle会被执行
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingGifImage animatedImage: UIImage!, sourceAssets asset: Any!) {
        
    }
    // The picker should dismiss itself; when it dismissed these handle will be called.
    // If isOriginalPhoto is YES, user picked the original photo.
    // You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
    // The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
    // 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
    // 如果isSelectOriginalPhoto为YES，表明用户选择了原图
    // 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
    // photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        
        self.selectedPhotos = photos
        self.selectedAssets = assets
        // 上传图片
        self.uploadPhoto()
    }
    // 用户点击了取消
    func tz_imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        print("用户点击了取消")
    }
    // 决定asset显示与否
    func isAssetCanSelect(_ asset: Any!) -> Bool {
        return true
    }
    // 决定相册显示与否
    func isAlbumCanSelect(_ albumName: String!, result: Any!) -> Bool {
        return true
    }
    
}









